<!-- 商品城市配置 -->
<template>
    <div>
        <a-page-header
            style="border: 1px solid rgb(235, 237, 240);background:#fff"
            :title="`${storehouse}-城市配置`"
            @back="() => $router.go(-1)"
        >
        <div class="table-page-search-wrapper">
            <a-form layout="inline">
                <a-row type="flex" justify="space-between" :gutter="48">
                    <a-col :md="16">
                    </a-col>
                    <a-col :md="8">
                        <a-form-item >
                            <a-button style="margin-left: 20px" type="primary" icon="plus" @click="add()">新增</a-button>
                            <!-- <a-button style="margin-left: 20px" type="primary" icon="plus" @click="add('all')">新增整区</a-button> -->
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size}" size="small">
            <div slot="province" slot-scope="province,record">
                <div>{{province}}-{{record.city}}-{{record.area}}<span v-if="record.town != '0'">-{{record.town}}</span></div>
            </div>
            <div slot="storehouseId" slot-scope="storehouseId">
                <div v-for="(item,i) in storehouseList" :key="i">
                    <a-tag v-if="item.id == storehouseId" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="deliveryType" slot-scope="deliveryType">
                <div v-for="(item,i) in deliveryTypeList" :key="i">
                    <a-tag v-if="item.id == deliveryType" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="delivererName" slot-scope="delivererName,record">
                <div v-if="record.deliveryType == '0'">{{delivererName}}</div>
                <div v-else>-</div>
            </div>
            <div slot="delivererPhone" slot-scope="delivererPhone,record">
                <div v-if="record.deliveryType == '0'">{{delivererPhone}}</div>
                <div v-else>-</div>
            </div>
            <div slot="operation2" slot-scope="text,record">
                <a-button type="link" @click="operation(record,'0')">查看</a-button>
            </div>
            <div slot="operation1" slot-scope="text,record">
                <div v-if="record.deliveryType == '0'">
                    <a-button type="link" @click="operation(record,'1')">查看</a-button>
                </div>
                <div v-else>-</div>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="开" un-checked-children="关" disabled :checked="status == 1 ? true : false" />
            </div>
            <template slot="operation" slot-scope="text, record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="update(record)">修改</a-button>
                    <a-popconfirm
                        title="是否确认删除当前配送城市配置?"
                        ok-text="Yes"
                        cancel-text="No"
                        @confirm="del(record)"
                    >
                        <a-button type="link" class="errorColor" >删除</a-button>
                    </a-popconfirm>
                </div>
            </template>
        </a-table>
        </a-page-header>

        <!-- 添加、修改商品城市配置 -->
        <a-modal
            title="添加、修改商品城市配置"
            :visible="visible"
            :confirm-loading="confirmLoading"
            @ok="handleOk"
            @cancel="visible = false"
            width="90%"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="省份">
                        <a-select v-model="provinces" placeholder="请选择" allowClear @change="selProvince">
                            <a-select-option v-for="(item,i) in provinceList" :key="i" :value="item.areaId + ',' + item.areaName">{{item.areaName}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="城市">
                        <a-select v-model="citys" placeholder="请选择" allowClear @change="selCity">
                            <a-select-option v-for="(item,i) in cityList" :key="i" :value="item.areaId + ',' + item.areaName">{{item.areaName}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="区域">
                        <a-select v-model="areas" placeholder="请选择" allowClear @change="selArea">
                            <a-select-option v-for="(item,i) in areaList" :key="i" :value="item.areaId + ',' + item.areaName">{{item.areaName}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <!-- <a-form-item label="区域">
                        <a-select v-model="item.area" v-if="!isAdd" placeholder="请选择" allowClear>
                            <a-select-option v-for="(item,i) in areaList" :key="i" :value="item.label">{{item.label}}</a-select-option>
                        </a-select>
                        <a-descriptions v-else :title="area.label" v-for="area in addAreaDeliverysList" :key="area.label" bordered>
                            <a-descriptions-item label="仓库" >
                                <a-select v-model="area.storehouseId" placeholder="请选择">
                                    <a-select-option v-for="(itm) in storehouseList" :value="itm.id.toString()" :key="itm.id">{{itm.name}}</a-select-option>
                                </a-select> 
                            </a-descriptions-item>
                            <a-descriptions-item label="配送方式" >
                                <a-radio-group v-model="area.deliveryType" >
                                    <a-radio v-for="itm in deliveryTypeList" :value="parseInt(itm.id)" :key="itm.id">{{itm.name}}</a-radio>
                                </a-radio-group>
                            </a-descriptions-item>
                            <a-descriptions-item label="骑手信息" >
                                <a-select v-model="area.delivererUserId" >
                                    <a-select-option v-for="(itm) in ridersList" :value="itm.userId" :key="itm.userId">{{itm.name}}</a-select-option>
                                </a-select>
                            </a-descriptions-item>
                        </a-descriptions>
                    </a-form-item> -->
                    <a-form-item label="街道" v-if="item.id == ''">
                        <a-select v-model="item.town" placeholder="请选择" mode="multiple" allowClear>
                            <a-select-option v-for="(item,i) in townList" :key="i" :value="item.areaName">{{item.areaName}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="街道" v-else>
                        <a-select v-model="item.town" placeholder="请选择" allowClear>
                            <a-select-option v-for="(item,i) in townList" :key="i" :value="item.areaName">{{item.areaName}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <!-- <a-form-item label="仓库名称" v-if="!isAdd">
                        <a-select v-model="item.storehouseId" placeholder="请选择">
                            <a-select-option v-for="(item) in storehouseList" :value="item.id.toString()" :key="item.id">{{item.name}}</a-select-option>
                        </a-select> 
                    </a-form-item> -->
                    <a-form-item label="配送方式" v-if="!isAdd">
                        <a-radio-group v-model="item.deliveryType" >
                            <a-radio v-for="item in deliveryTypeList" :value="parseInt(item.id)" :key="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="骑手信息" v-if="item.deliveryType == '0' && !isAdd">
                        <a-select v-model="item.delivererUserId" >
                            <a-select-option v-for="(item) in ridersList" :value="item.userId" :key="item.userId">{{item.name}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-radio-group v-model="item.status" >
                            <a-radio value="0">关闭</a-radio>
                            <a-radio value="1">开启</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryGoodsCityConfig , updateGoodsCityConfig , queryGoodsCommonConfig , queryRiderUserInfo } from '@/api/newMall';
import { queryAreaInfo} from '@/api/brand';
import area from '@/assets/area';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            storehouse: JSON.parse(localStorage.getItem('storehouseName')),
            storehouseId: JSON.parse(localStorage.getItem('storehouseId')),
            dataList: [],
            total: 0,
            page: 1,
            size: 10,
            storehouseList: [], // 仓库列表
            deliveryTypeList: [
                { id: 0, name: '极速送达'},{ id: 1, name: '快递'},
            ], // 配送方式
            item: {
                id: '',
                province: '',
                city: '',
                area: '',
                town: '', // 城镇
                storehouseId: undefined, // 仓库ID
                deliveryType: '0', // 配送方式
                delivererUserId: undefined, // 配送员ID
                status: '1',
            },
            confirmLoading: false,
            isload: false,
            visible: false,
            columns,
            drawerVisible: false,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            provinceList: [],
            cityList: [],
            areaList: [],
            townList: [],
            ridersList: [], // 骑手列表
            addAreaDeliverysList: [],
            provinces: '',
            citys: '',
            areas: '',
            isAdd: true,
        };
    },
    async created(){
        try {
            // var list = []
            // for (const key in area.province_list) {
            //     if (area.province_list.hasOwnProperty(key)) {
            //         list.push({
            //             'label': area.province_list[key],
            //             'value': `${key},${area.province_list[key]}`,
            //             isLeaf: false,
            //         })
            //     }
            // }
            this.provinceList = await this._queryAreaInfo('0');
            await this.getStoreHouse();
            await this.getRiders();
            this.getData()
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: '网路丢失，请稍后再试！',
                duration: 8,
            })
        }
    },
    methods: {
        getData(){
            let _this = this
            _this.isload = true
            const params = {
                'brandId':_this.brandId,
                'storehouseId': _this.storehouseId,
                'page':_this.page - 1,
                'size':_this.size,
            }
            queryGoodsCityConfig(params)
            .then(res=>{
                _this.isload = false
                if(res.success){
                    _this.dataList = res.data.content
                    _this.total = res.data.totalElements
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 获取商品仓库信息
        getStoreHouse(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'type': '0',
                    'page': 0,
                    'size': 99,
                };
                queryGoodsCommonConfig(params)
                .then(res=>{
                    if(res.success){
                        _this.storehouseList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取骑手信息
        getRiders(){
            let _this = this;
            return new Promise((resolve,reject) => {
                const params = {
                    'brandId':_this.brandId,
                    'page': 0,
                    'size': 99,
                };
                queryRiderUserInfo(params)
                .then(res=>{
                    if(res.success){
                        _this.ridersList = res.data.content;
                        resolve();
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(type){
            if(!this.brandId){
                this.$message.warning('请先选择品牌')
                return
            }
            this.item.id = ''
            this.item.brandId = this.brandId
            this.item.province = undefined
            this.provinces = undefined
            this.item.city = undefined
            this.citys = undefined
            this.item.area = undefined
            this.areas = undefined
            this.item.town = undefined
            this.item.status = '1'
            this.item.deliveryType = 0
            this.item.storehouseId = undefined
            this.item.delivererUserId = undefined
            console.log(this.item,'item')
            if(type == 'all'){
                this.addAreaDeliverysList = []
                this.isAdd = true;
            }else{
                this.isAdd = false;
            }
            this.visible = true
        },
        // 修改
        update(item){
            let _this = this;
            _this.item = JSON.parse(JSON.stringify(item))
            // for (const key in area.province_list) {
            //     if (area.province_list.hasOwnProperty(key)) {
            //         if(area.province_list[key].indexOf(item.province) != -1){
            //             _this.provinces = `${key},${area.province_list[key]}`;
            //         }
            //     }
            // }
            var proItem = _this.provinceList.find(itm => itm.areaName == item.province)
            _this.provinces = `${proItem.areaId},${proItem.areaName}`;
            _this.selProvince('1');
            // for (const key in area.city_list) {
            //     if (area.city_list.hasOwnProperty(key)) {
            //         if(area.city_list[key].indexOf(item.province) != -1){
            //             _this.citys = `${key},${area.city_list[key]}`;
            //         }
            //     }
            // }
            this.isAdd = false;
            _this.visible = true
        },
        // 确定添加、修改
        async handleOk(){
            let _this = this
            if(_this.item.province === undefined){
                this.$message.warning('请选择省份');
                return
            }
            if(_this.item.city === undefined){
                this.$message.warning('请选择城市');
                return
            }
            if(_this.isAdd){
                console.log(_this.addAreaDeliverysList,'addAreaDeliverysList')
                _this.allAdd();
                return;
            }
            if(_this.item.area === undefined){
                this.$message.warning('请选择区域');
                return
            }
            // if(_this.item.storehouseId === undefined){
            //     this.$message.warning('请选择仓库');
            //     return
            // }
            if(_this.item.deliveryType == '0'){
                if(_this.item.delivererUserId === undefined){
                    this.$message.warning('请选择配送员信息');
                    return
                }
            }
            if(_this.item.id == '' && _this.item.town){
                let list = _this.item.town;
                for (let index = 0; index < list.length; index++) {
                    const element = list[index];
                    const params = {
                        'id':_this.item.id,
                        'brandId':_this.brandId,
                        'province':_this.item.province,
                        'city':_this.item.city,
                        'area':_this.item.area,
                        'town':element,
                        'storehouseId':_this.storehouseId,
                        'deliveryType':_this.item.deliveryType,
                        'delivererUserId':_this.item.delivererUserId,
                        'status':_this.item.status,
                    }
                    try {
                        await _this._saveData(params);
                    } catch (error) {
                        _this.$notification['error']({
                            message: '提示',
                            description: error,
                            duration: 8,
                        })
                    }
                }
                _this.$notification['success']({
                    message: '提示',
                    description: '添加成功',
                    duration: 8,
                })
                _this.visible = false
                _this.getData()
            }else{
                _this.confirmLoading = true
                const params = {
                    'id':_this.item.id,
                    'brandId':_this.brandId,
                    'province':_this.item.province,
                    'city':_this.item.city,
                    'area':_this.item.area,
                    'town':_this.item.town ?? '0',
                    'storehouseId':_this.storehouseId,
                    'deliveryType':_this.item.deliveryType,
                    'delivererUserId':_this.item.delivererUserId,
                    'status':_this.item.status,
                }
                try {
                    await _this._saveData(params);
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.item.id == '' ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                    _this.visible = false
                    _this.getData()
                } catch (error) {
                    _this.$notification['error']({
                        message: '提示',
                        description: error,
                        duration: 8,
                    })
                }
            }
            
        },
        _saveData(params){
            let _this = this;
            return new Promise((resolve,reject) => {
                updateGoodsCityConfig(params)
                .then(res=>{
                    _this.confirmLoading = false
                    if(res.success){
                        // _this.$notification['success']({
                        //     message: '提示',
                        //     description: _this.item.id == '' ? '添加成功' : '修改成功',
                        //     duration: 8,
                        // })
                        // _this.visible = false
                        // _this.getData()
                        resolve();
                    }else{
                        // _this.$notification['error']({
                        //     message: '提示',
                        //     description: res.errMessage,
                        //     duration: 8,
                        // })
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 删除
        del(item){
            let _this = this
            const params = {
                'brandId':item.brandId,
                'id':item.id,
                'isDelete':1,
            }
            updateGoodsCityConfig(params)
            .then(res=>{
                if(res.success){
                    _this.visible = false
                    _this.getData()
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 选择省份
        // selProvince(type){
        //     if(type != '1'){
        //         this.item.city = undefined;
        //     }
        //     if(this.provinces){
        //         this.item.province = this.provinces.split(',')[1]
        //         var provinceId = this.provinces.split(',')[0]
        //         console.log(provinceId,'provinceId')
        //         var list = [];
        //         for (const key in area.city_list) {
        //             // console.log(key,'key')
        //             if (area.city_list.hasOwnProperty(key) && key.substring(0, 2) == provinceId.substring(0,2)) {
        //                 list.push({
        //                     'label': area.city_list[key],
        //                     'value': `${key},${area.city_list[key]}`,
        //                     isLeaf: false,
        //                 })
        //             }
        //         }
        //         this.cityList = list;
        //     }else{
        //         this.provinces = ''
        //         this.cityList = [];
        //     }
        // },
        // // 选择城市
        // selCity(type){
        //     if(type != '1'){
        //         this.item.area = undefined;
        //     }
        //     if(this.citys){
        //         this.item.city = this.citys.split(',')[1]
        //         var cityId = this.citys.split(',')[0]
        //         console.log(cityId,'cityId')
        //         var list = [];
        //         var addList = [];
        //         for (const key in area.county_list) {
        //             // console.log(key,'key')
        //             if (area.county_list.hasOwnProperty(key) && key.substring(0, 4) == cityId.substring(0,4)) {
        //                 list.push({
        //                     'label': area.county_list[key],
        //                     'value': `${area.county_list[key]}`,
        //                     isLeaf: false,
        //                 })
        //                 addList.push({
        //                     'storehouseId':undefined,
        //                     'deliveryType':undefined,
        //                     'delivererUserId':undefined,
        //                     'label': area.county_list[key]
        //                 })
        //             }
        //         }
        //         this.areaList = list;
        //         this.addAreaDeliverysList = addList
        //     }else{
        //         this.citys = ''
        //         this.areaList = [];
        //     }
        // },
        // 获取省市区
        async _queryAreaInfo(areaParentId){
            return new Promise((resolve,reject) => {
                queryAreaInfo(areaParentId)
                .then(res => {
                    if(res.success){
                        resolve(res.data)
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 选择省
        async selProvince(type){
            let _this = this;
            if(this.provinces){
                this.item.province = this.provinces.split(',')[1]
                var provinceId = this.provinces.split(',')[0]
                console.log(provinceId,'provinceId')
                var list = [];
                try {
                    list = await _this._queryAreaInfo(provinceId);
                } catch (error) {
                    _this.$notification['error']({
                        message: '提示',
                        description: error,
                        duration: 8,
                    })
                }
                if(type != '1'){
                    this.item.city = undefined;
                    this.citys = undefined;
                }else{
                    var item = list.find(itm => itm.areaName == _this.item.city)
                    this.citys = `${item.areaId},${item.areaName}`
                    this.selCity('1');
                }
                this.cityList = list;
            }else{
                this.provinces = ''
                this.cityList = [];
            }
        },
        // // 选择城市
        async selCity(type){
            let _this = this;
            if(this.citys){
                this.item.city = this.citys.split(',')[1]
                var cityId = this.citys.split(',')[0]
                console.log(cityId,'cityId')
                var list = [];
                // var addList = [];
                try {
                    list = await _this._queryAreaInfo(cityId);
                } catch (error) {
                    _this.$notification['error']({
                        message: '提示',
                        description: error,
                        duration: 8,
                    })
                }
                if(type != '1'){
                    this.item.area = undefined;
                    this.areas = undefined;
                }else{
                    var item = list.find(itm => itm.areaName == _this.item.area)
                    this.areas = `${item.areaId},${item.areaName}`
                    this.selArea('1');
                }
                this.areaList = list;
                // this.addAreaDeliverysList = addList
            }else{
                this.citys = ''
                this.areaList = [];
            }
        },
        // 选择区域
        async selArea(type){
            let _this = this;
            if(type != '1'){
                this.item.town = undefined;
            }
            if(this.areas){
                this.item.area = this.areas.split(',')[1]
                var areaId = this.areas.split(',')[0]
                var list = [];
                try {
                    list = await _this._queryAreaInfo(areaId);
                } catch (error) {
                    _this.$notification['error']({
                        message: '提示',
                        description: error,
                        duration: 8,
                    })
                }
                console.log(this.item.area,'area')
                this.townList = list;
            }else{
                this.areas = ''
                this.townList = [];
            }
        },
        // 整区添加
        async allAdd(){
            let _this = this;
            try {
                var array = _this.addAreaDeliverysList;
                var areaList = [];
                for (let index = 0; index < array.length; index++) {
                    const item = array[index];
                    console.log(item,'item')
                    if(item.storehouseId != undefined && item.deliveryType !== '' && ((item.deliveryType == '0' && item.delivererUserId != undefined) || item.deliveryType == '1')){
                        const params = {
                            'brandId':_this.brandId,
                            'province':_this.item.province,
                            'city':_this.item.city,
                            'area':item.label,
                            'storehouseId':item.storehouseId,
                            'deliveryType':item.deliveryType,
                            'delivererUserId':item.delivererUserId,
                            'status':_this.item.status,
                        }
                        areaList.push(item.label)
                        console.log(params,'params')
                        try {
                            await _this.addData(params);
                        } catch (error) {
                            _this.$notification['error']({
                                message: '提示',
                                description: error,
                                duration: 8,
                            })
                        }
                    }
                }
                _this.$confirm({
                    title: '温馨提示',
                    content: `${areaList.join(',')}已成功添加，请注意查看`,
                    okText: '确定',
                    okType: 'danger',
                    onOk() {
                        console.log('OK');
                        _this.visible = false;
                    },
                    onCancel() {
                        console.log('Cancel');
                        _this.visible = false;
                    },
                });
                _this.getData();
            } catch (error) {
                
            }
        },
        addData(params){
            return new Promise((resolve,reject) => {
                updateGoodsCityConfig(params)
                .then(res=>{
                    if(res.success){
                        resolve()
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        operation(item,type){
            console.log(item)
            localStorage.setItem('province',JSON.stringify(item.province))
            localStorage.setItem('city',JSON.stringify(item.city))
            localStorage.setItem('area',JSON.stringify(item.area))
            if(type == '0'){
                // 跳转花店排序
                this.$router.push({ path: '/member/shoppingRank'})
            }else{
                localStorage.setItem('delivererUserId',JSON.stringify(item.delivererUserId))
                localStorage.setItem('delivererName',JSON.stringify(item.delivererName))
                // 跳转订单排序
                this.$router.push({ path: '/newMall/goodsOrder/riderOrder'})
            }
        }
    }
}

</script>
<style scoped>
td{
    width: 140px;
    height: 30px;
}
.green{
    color: #87d068;
}
</style>